package database

import (
	"context"
	"fmt"
	"log"

	"go-server-demo/ent"
	"go-server-demo/internal/config"

	_ "github.com/go-sql-driver/mysql"
)

func NewEntClient(cfg *config.Config) *ent.Client {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=%t&loc=%s",
		cfg.Database.Username,
		cfg.Database.Password,
		cfg.Database.Host,
		cfg.Database.Port,
		cfg.Database.DBName,
		cfg.Database.Charset,
		cfg.Database.ParseTime,
		cfg.Database.Loc,
	)

	client, err := ent.Open(cfg.Database.Driver, dsn)
	if err != nil {
		log.Fatalf("failed opening connection to database: %v", err)
	}

	// 运行数据库迁移
	if err := client.Schema.Create(context.Background()); err != nil {
		log.Fatalf("failed creating schema resources: %v", err)
	}

	return client
}
